﻿#region Using namespaces

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Text;

using BOL.IO;
using BOL.Apps.GeneNetworkBrowser;
#endregion

namespace BOL.Apps.GeneNetworkBrowser.IO
{
    public class NCRReader : IReader<NCR>
    {
        #region Private variables

        private StreamReader _sr;

        #endregion

        #region Constructors

        public NCRReader(FileStream fs)
        {
            this._sr = new StreamReader(fs);
        }

        public NCRReader(string path) : this(new FileStream(path, FileMode.Open)) { }

        #endregion

        #region Public methods

        public NCR Read()
        {
            char[] delimiters = new char[1] { '\t' };
            string line = String.Empty;
            string[] temp; // temporary string array splitted by delimiter

            List<string> probesetIds = new List<string>();
            List<double[]> expressionValues = new List<double[]>();
            
            // Read ids...
            line = _sr.ReadLine();
            temp = line.Split(delimiters);
            int numberOfIds = temp.Length - 1;
            var ids = new string[numberOfIds];
            var times = new double[numberOfIds];
            var endPoints = new bool[numberOfIds];

            Array.Copy(temp, 1, ids, 0, numberOfIds);
            string varName = String.Empty;
            string[] varValue = new string[numberOfIds];

            // Read variables
            var variables = new ObservableCollection<NCR.Covariate>();
            while (!_sr.EndOfStream)
            {
                line = _sr.ReadLine();
                temp = line.Split(delimiters);
                varName = temp[0];
                Array.Copy(temp, 1, varValue, 0, numberOfIds);

                if (varName == "OS")
                    times = varValue.Select(x => Double.Parse(x)).ToArray();
                else if (varName == "STATUS")
                {
                    endPoints = varValue.Select(x => (x == "1") ? true : false).ToArray();
                    break;
                }
                else
                    variables.Add(new NCR.Covariate(varName, varValue));
            }

            while (!_sr.EndOfStream)
            {
                line = _sr.ReadLine();
                temp = line.Split(delimiters);
                varName = temp[0];
                Array.Copy(temp, 1, varValue, 0, numberOfIds);

                probesetIds.Add(varName);
                expressionValues.Add(varValue.Select(x => Double.Parse(x)).ToArray());
            }

            return new NCR(String.Empty, ids, times, endPoints, probesetIds.ToArray(), expressionValues.ToArray(), variables);
        }

        public void Close()
        {
            _sr.Close();
        }

        #endregion
    }
}
